package com.pro.common.service.service;

import com.alibaba.nacos.api.config.ConfigFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.common.packagescan.resource.ClassPathResource;
import com.pro.common.service.properties.NacosConfigReadProperties;
import com.pro.framework.api.FrameworkConst;
import lombok.Cleanup;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

@Slf4j
public class NacosConfigInitService {


    public static final String TYPE_YAML = "yaml";
    private static ConfigService configService;
    private final NacosConfigReadProperties nacosConfigReadProperties;

    @SneakyThrows
    public NacosConfigInitService(NacosConfigReadProperties nacosConfigReadProperties) {
        log.info("NacosConfigInitService {}", nacosConfigReadProperties);

        this.nacosConfigReadProperties = nacosConfigReadProperties;
        initializeConfig();
    }

    /**
     * 初始化配置（仅首次）
     */
    @SneakyThrows
    public void initializeConfig() {
        Properties properties = new Properties();
        properties.put("serverAddr", nacosConfigReadProperties.getServerAddr());
        properties.put("namespace", nacosConfigReadProperties.getNamespace());
        properties.put("username", nacosConfigReadProperties.getUsername());
        properties.put("password", nacosConfigReadProperties.getPassword());
        configService = ConfigFactory.createConfigService(properties);
        String config = getConfig("global-dev.yaml");
//        log.info("==========config {}",config);
        String initDataids = nacosConfigReadProperties.getInitDataids();
        if (initDataids != null) {
            for (String dataId : initDataids.split(",")) {
                String localConfig = this.loadLocalConfig(dataId);
                if (localConfig == null || localConfig.isEmpty()) {
                    continue; // 本地没有初始配置
                }
                if (!isConfigCenterExist(dataId)) {
                    this.updateCenterConfig(dataId, localConfig);
                }
            }
        }
    }

    // 获取 Nacos 配置（私有方法）
    @SneakyThrows
    public String getConfig(String dataId) {
        String config = FrameworkConst.Str.EMPTY;
//        try {
        config = configService.getConfig(dataId, nacosConfigReadProperties.getGroup(), 5000);
//        } catch (NacosException e) {
////            throw new RuntimeException(e);
////            return config;
//        }
        return config;
    }

    // 更新配置到 Nacos（私有方法）
    @SneakyThrows
    public void updateCenterConfig(String dataId, String configContent) {
        boolean success = configService.publishConfig(dataId, nacosConfigReadProperties.getGroup(), configContent,
                TYPE_YAML);
        log.info("updateCenterConfig {} {} {}", success, dataId, configContent.length());
    }

    // 加载本地配置文件（私有方法）
    @SneakyThrows
    private String loadLocalConfig(String dataId) {
        ClassPathResource resource = new ClassPathResource(dataId);
        if (!resource.exists()) {
            return null;
        }
        @Cleanup InputStream inputStream = resource.getInputStream();
        return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
    }


    @SneakyThrows
    private boolean isConfigCenterExist(String dataId) {
        return getConfig(dataId) != null && !getConfig(dataId).isEmpty();
    }

}
